package org.wxd.media.mongodb;

import com.mongodb.gridfs.GridFSFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Repository;
import org.wxd.common.utils.StringUtil;
import org.wxd.media.domain.GridFsHelper;
import org.wxd.media.domain.Media;
import org.wxd.media.domain.MediaOperations;

import java.io.InputStream;
import java.util.Map;
import java.util.Optional;

/**
 * Created by wangxd on 2016/11/1.
 */
@Repository
public class MongoMediaOperations implements MediaOperations {


    @Autowired
    GridFsTemplate fsTemplate;
    @Autowired
    GridFsOperations fsOps;


    @Override
    public Media store(InputStream stream, Media media) {
        GridFSFile fsFile = fsTemplate.store(stream, media.name(), media.contentType(), media);
        Map metaData = fsFile.getMetaData().toMap();
        metaData.remove(Media.CLASS);
        long createTime = fsFile.getUploadDate().getTime();
        long expireTime = (long) metaData.remove(Media.EXPIRE_TIME_META_NAME);
        return Media.newBuilder().id(fsFile.getId().toString())
                .name(fsFile.getFilename())
                .contentType(fsFile.getContentType())
                .suffix((String) metaData.get(Media.SUFFIX))
                .moreInfo((Map<String, String>) metaData.get(Media.MORE_INFO))
                .size(fsFile.getLength()).createTime(createTime).expireTime(expireTime).build();
    }

    @Override
    public Optional<Media> ofCheckSum(String checkSum) {
        if (!StringUtil.isNotBlank(checkSum)) return Optional.empty();
        return Optional.ofNullable(GridFsHelper.asEntity(fsOps.findOne(this.forCheckSumQuery(checkSum))));
    }

    private Query forCheckSumQuery(String checkSum) {
        return Query.query(Criteria.where(Media.MD5).is(checkSum));
    }
}
